<?php

namespace app\admin\controller;

use app\admin\model\SstalinkDevice;
use app\admin\model\SstalinkOrganization;
use app\admin\model\SstalinkSensor;
use app\common\controller\Backend;

use think\Controller;
use think\Cookie;
use think\Db;
use think\exception\PDOException;
use think\Request;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Devices extends Backend
{

    /**
     * SstalinkDevice模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('SstalinkDevice');

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            $admin = Session::get("admin");
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where("ownerid", $admin->id)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where("ownerid", $admin->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $admin = Session::get("admin");
                foreach ($params as $k => &$v) {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params["ownerid"] = $admin->id;
                    $params["createtime"] = date("Y-m-d H:i:s", time());
                    $params["modifytime"] = $params["createtime"];
                    $params["deviceid"] = "";
                    $params["secret"] = "";
                    $result = $this->model->save($params);
                    if ($result !== false) {
                        $deviceid = substr(sha1($this->model->id . $this->model->name . time() . $this->create_password(10)), 0, 9);
                        while (SstalinkDevice::get(["deviceid" => $deviceid])) {
                            $deviceid = substr(sha1($this->model->id . $this->model->name . time() . $this->create_password(10)), 0, 9);
                        }
                        $secrect = bin2hex(hash("sha256", $this->model->id . $this->model->name . time() . $this->create_password(10), true));
                        $this->model->save(["deviceid" => $deviceid, "secret" => $secrect]);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = SstalinkDevice::get(["deviceid" => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $admin = Session::get("admin");
                $params['ownerid'] = $admin->id;
                foreach ($params as $k => &$v) {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }

    /**
     * 删除
     */
    public function del($ids = NULL)
    {
        $count = SstalinkDevice::destroy(["deviceid" => $ids]);
        if ($count) {
            $sensors = SstalinkSensor::all(["deviceid" => $ids]);
            foreach ($sensors as $key => $value) {
                switch ($value->datatype) {
                    case 0:
                        Db::table("sstalink_data_number")->where("sensorid", $value->id)->delete();
                        break;
                    case 1:
                        Db::table("sstalink_data_text")->where("sensorid", $value->id)->delete();
                        break;
                    case 2:
                        Db::table("sstalink_data_point")->where("sensorid", $value->id)->delete();
                        break;
                    case 3:
                        Db::table("sstalink_data_base64")->where("sensorid", $value->id)->delete();
                        break;
                    case 4:
                        Db::table("sstalink_data_boolean")->where("sensorid", $value->id)->delete();
                        break;
                }
            }
            Db::table("sstalink_sensor")->where("deviceid", $ids)->delete();
            $this->success();
        }
    }

    public function unlock($ids = null)
    {
        $row = $this->model->get($ids);
        $row->state = $row->state == -1 ? 0 : -1;
        $row->save();
        $this->redirect("devices/index");
    }

    function create_password($pw_length)
    {
        $randpwd = "";
        for ($i = 0; $i < $pw_length; $i++) {
            $randpwd .= chr(mt_rand(33, 126));
        }
        return $randpwd;
    }
}
